﻿using AmiDraw.Lib.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace AmiDraw.Lib.Factory
{
    public class DrawerFactory
    {
        public string PackName { get; }
        public List<DrawResult> DrawResults { get; }
        public ResultQueryMode Mode { get; }

        public DrawerFactory(string packName, List<DrawResult> drawResults, ResultQueryMode mode)
        {
            PackName = packName;
            DrawResults = drawResults;
            Mode = mode;
        }

        public Bitmap GenerateImage()
        {
            var packDir = PathFactory.GetPackPath(PackName, Mode);

            AcPackInfo packInfo = JsonFactory.LoadJson<AcPackInfo>(
                Path.Combine(packDir, "info.json"));

            var multiplotdrawers = JsonFactory.LoadMultiplotElementJson(
                Path.Combine(packDir, "multiplotdrawer.json"));

            Bitmap bitmap = new Bitmap(packInfo.ImageWidth, packInfo.ImageHeight);

            using (Graphics graphics = Graphics.FromImage(bitmap))
            {


                foreach (var drawer in multiplotdrawers)
                {
                    switch (drawer.Name)
                    {
                        case "Text":
                            DrawText(graphics, drawer as TextElement);
                            break;
                        case "Rectangle":
                            DrawRect(graphics, drawer as RectangleElement);
                            break;
                        case "Image":
                            DrawImage(graphics, drawer as ImageElement);
                            break;

                    }
                }

                return bitmap;
            }


        }

        private void DrawText(Graphics graphics, TextElement element)
        {


            var text = ReplaceCommonPlacehold(element.Text, DrawResults);

            var rect = new RectangleF((float)element.X, (float)element.Y, (float)element.Width, (float)element.Height);
            var font = new Font("Airal", 14);
            var brush = new SolidBrush(Color.FromName(element.Color));


            graphics.DrawString(text, font, brush, rect);

        }

        private void DrawImage(Graphics graphics, ImageElement element)
        {
            var resKey = element.ImageResKey;

            if (string.IsNullOrEmpty(resKey))
                return;

            resKey = ReplaceCommonPlacehold(resKey, DrawResults);


            var match = Regex.Match(resKey, @"\[卡片图片{index:([0-9]*)}\]");
            if (match == null || !match.Success)
            {
                //没找到，说明是静态资源
            }
            else
            {
                //图片资源
                var index = int.Parse(match.Groups[1].Value);
                if (DrawResults.Count <= index)
                    return;
                resKey = DrawResults[index].CardInfo.ImageResKey;
            }


            if (resKey == "")
                return;
            var rect = new RectangleF((float)element.X, (float)element.Y, (float)element.Width, (float)element.Height);

            using (var stream = new FileStream(PathFactory.GetResImagePath(PackName, resKey, Mode), FileMode.Open))
            {
                using (var image = Image.FromStream(stream))
                {
                    //按照比例重新决定rect

                    var ratio = Math.Min(rect.Width /image.Width, rect.Height /image.Height);

                    var newRect = new RectangleF((float)element.X, (float)element.Y, image.Width * ratio, image.Height * ratio);
                    newRect.X = rect.X + (rect.Width - newRect.Width) / 2;
                    newRect.Y = rect.Y + (rect.Height - newRect.Height) / 2;
                    graphics.DrawImage(image, newRect);
                }

            }

        }
        private static void DrawRect(Graphics graphics, RectangleElement element)
        {
            var rect = new RectangleF((float)element.X, (float)element.Y, (float)element.Width, (float)element.Height);
            var brush = new SolidBrush(Color.FromName(element.Color));

            graphics.FillRectangle(brush, rect);
        }

        private static string ReplaceCommonPlacehold(string text,List<DrawResult> drawResults)
        {
            var matches = Regex.Matches(text, @"\[(.*?){index:([0-9]*)}\]");

            foreach (Match match in matches)
            {

                var targetIndex = int.Parse(match.Groups[2].Value);
                if (drawResults.Count <= targetIndex)
                    continue;
                var drawResult = drawResults[targetIndex];

                //[卡片名{index:}] [卡片描述{index:}] [等级名{index:}] [等级描述{index:}] [等级概率{index:}]
                Dictionary<string, string> dic = new()
                {
                    { "卡片名", drawResult.CardInfo.Name },
                    { "卡片描述", drawResult.CardInfo.Description },
                    { "等级名", drawResult.LevelInfo.Name },
                    { "等级描述", drawResult.LevelInfo.Description },
                    { "等级概率", (drawResult.LevelInfo.Ratio / drawResult.SumRatio).ToString() },

                };

                foreach (var item in dic)
                {
                    if (match.Groups[1].Value == item.Key)
                    {
                        text = text.Replace(match.Value, item.Value);
                    }
                }
            }
            return text;
        }
    }
}
